﻿var opentabs = 6, init = 0, _menusData; //允许打开的TAB数量
$(function(){
    $('#tabs').tabs({
        tools: [{
            iconCls: 'icon-arrow_refresh icon16 ',
            handler: function() {
                var currentTab = $('#tabs').tabs('getSelected');
                var tab = $('#tabs').tabs('getSelected');
                var iframe = $(currentTab.panel('options').content);
                var src = iframe.attr('src');
                if((typeof src) == 'undefined'){
                    return false;
                }
                $('#tabs').tabs('update', {
                    tab: currentTab,
                    options: {
                        content: base.createFrame(src)
                    }
                });
                return false;
            }
        }, {
            iconCls: 'panel-tool-close',
            handler: function() {
                var alltabs = $('#tabs').tabs('tabs');
                var allTabtitle = [];
                var count = 0;
                $.each(alltabs, function (i, n) {
                    allTabtitle.push($(n).panel('options').title);
                    count += 1;
                });
                if(count > 1){
                    $.messager.confirm("操作提示", '确定要关闭所有打开的窗口么？', function(r){
                        if (r){
                            $.each(allTabtitle, function (i, n) {
                                if (n != '欢迎使用') {
                                    $('#tabs').tabs('close', n);
                                }
                            });
                        }
                    });
                }else {
                    $.messager.alert('系统提示', '当前无可操作的工作窗口', 'warning');
                }
            }
        }],
        onContextMenu: function(e, title) {
            e.preventDefault();
            $('#closeMenu').menu('show', {
                left: e.pageX,
                top: e.pageY
            });
            $('#tabs').tabs('select', title);
        }
    });
    checkMenu();
    $('#clean-cache').click(function () {
        $.messager.confirm('系统提示', '清除当前缓存重新自动登录?', function(r){
            if (r){
                var token = store.get('easy-admin-pc-token');
                if((typeof token) != 'undefined'){
                    var param = {
                        url: constant.route.user.check
                    }
                    var request = http.get(param);
                    request.done(function (data) {
                        store.clear();
                        auth.cache(data.result);
                        window.location.reload();
                    })
                }else{
                    store.clear();
                }
            }
        });
    })
    initCommonDataCache();
    $('#query-day').combobox({
        onChange:function(newValue,oldValue){
            getLog();
        }
    });
    getLog();
    getCount();

    // 修改密码
    $('#edit-password').click(function () {
        kit.form.clean('#opt-form-password');
        var config = {
            title: '密码修改',
            top:20,
            fit:false,
            draggable:false,
            closed: true,
            resizable: false,
            cache: false,
            modal: true,
            buttons: [{
                text:'修 改',
                iconCls:'icon-accept icon16',
                handler:function(){
                    var data = kit.form.get('#opt-form-password');
                    if($.trim(data.password).length < 5 || $.trim(data.password).length >= 20){
                        kit.alert('旧密码长度必须在6个字符以上20个字符以下', 'warning');
                        return false;
                    }
                    if(data.password2 != data.password3){
                        kit.alert('您输入的2次新密码不一致', 'warning');
                        return false;
                    }
                    data['oldPwd'] = $.trim(data.password);
                    data['newPwd'] = $.trim(data.password2);
                    var param = {
                        url: constant.route.user.base + '/my-password',
                        data: data
                    };
                    var request = http.put(param);
                    request.done(function (d) {
                        kit.alert(d.message, 'success');
                        setTimeout(function () {
                            store.clear();
                            window.location.href = '/';
                        }, 3000)
                    })
                }
            },{
                iconCls:'icon-cancel icon16',
                text:'关 闭',
                handler:function(){
                    $('#update-password').dialog('close');
                }
            }]
        }
        $('#update-password').dialog(config);
        $('#update-password').dialog('open');
    })
    // 退出登录
    $('#login-out').click(function () {
        $.messager.confirm('系统提示', '是否要退出当前系统?', function(r){
            if (r){
                var param = {
                    url: constant.route.user.base + '/login-out'
                }
                var request = http.get(param);
                request.done(function (data) {
                    store.clear();
                    window.location.href = '/';
                })
            }
        });
    })
    // 用户信息
    var label = store.get('easy-admin-pc-label');
    var loginName = store.get('easy-admin-pc-login-name');
    var name = label.info.userName;
    name = (typeof name) == 'undefined' ? loginName : name;
    $('#login-name').html(name);
})

function checkMenu() {
    _menusData = store.get('easy-admin-pc-menu');
    if((typeof _menusData) != 'undefined'){
        try{
            base.initLeftMenu();
            base.tabClose();
            base.tabCloseEven();
        }catch (e){}
    }else{
        store.clear();
        window.location.href = '/';
    }
}
// 基础页面
var base = {
    initLeftMenu:function () {
        $("#nav").accordion({animate:false});
        $.each(_menusData, function(i, n) {
            var menuList ='';
            menuList +='<ul>';

            $.each(n.children, function(j, o) {
                var path = '/images/icon/32/'+o.icon.replace('icon-', '')+'.png';
                if(o.isHidden == 0){
                    menuList += '<li>' +
                        '<div>' +
                        '<a ref="'+o.id+'" href="#" rel="' + o.url + '" style="text-align: center;padding: 5px 0px 3px 0px;">' +
                        '<img src="'+path+'"/>' +
                        '<span class="nav" style="display: block;">&nbsp;' + o.name + '</span>' +
                        '</a>' +
                        '</div>' +
                        '</li> ';
                }
            })
            menuList += '</ul>';

            $('#nav').accordion('add', {
                title: n.name,
                content: menuList,
                iconCls: 'icon icon16 ' + n.icon
            });

        });
        $('.easyui-accordion li a').click(function(){
            var tabTitle = $(this).children('.nav').text();

            var url = $(this).attr("rel");
            var menuid = $(this).attr("ref");
            var icon = base.getIcon(menuid,icon);

            base.addTab(tabTitle,url,icon);
            $('.easyui-accordion li div').removeClass("selected");
            $(this).parent().addClass("selected");
        }).hover(function(){
            $(this).parent().addClass("hover");
        },function(){
            $(this).parent().removeClass("hover");
        });
        //选中第一个
        var panels = $('#nav').accordion('panels');
        var t = panels[0].panel('options').title;
        $('#nav').accordion('select', t);
    },
    getIcon:function (_menuId) {
        var icon = 'icon icon16 ';
        $.each(_menusData, function(i, n) {
            $.each(n.children, function(j, o) {
                if(o.id == _menuId){
                    icon += o.icon.replace('32', '');
                }
            })
        })
        return icon;
    },
	addTab:function (_subtitle, _url, _icon) {
        if (_url == "" || _url == "#")
            return false;
        var tabCount = $('#tabs').tabs('tabs').length;
        var hasTab = $('#tabs').tabs('exists', _subtitle);

        var add = function () {
            if(!hasTab){
                $('#tabs').tabs('add',{
                    title: _subtitle,
                    content: base.createFrame(_url),
                    closable: true,
                    icon: _icon
                });
            }else{
                $('#tabs').tabs('select',_subtitle);
                // $('#tab-refresh').click(); 点击菜单刷新当前页面
            }
        }
        if (tabCount > opentabs && !hasTab) {
            var msg = '<b>您当前打开了太多的页面，如果继续打开，会造成程序运行缓慢，无法流畅操作！</b>';
            $.messager.confirm("系统提示", msg, function (b) {
                if (b) add();
                else return false;
            });
        } else {
            add();
        }
        base.tabClose();
    },
    createFrame:function (_url) {
        var iframe = '<iframe scrolling="auto" frameborder="0"  src="' + _url + '" style="width:100%;height:100%;"></iframe>';
        return iframe;
    },
    tabClose:function () {
        /*双击关闭TAB选项卡*/
        $(".tabs-inner").dblclick(function(){
            var subtitle = $(this).children(".tabs-closable").text();
            $('#tabs').tabs('close',subtitle);
        })
        /*为选项卡绑定右键*/
        $(".tabs-inner").bind('contextmenu',function(e){
            $('#tab-menu').menu('show', {
                left: e.pageX,
                top: e.pageY
            });
            var subtitle =$(this).children(".tabs-closable").text();
            $('#tab-menu').data("currtab",subtitle);
            $('#tabs').tabs('select',subtitle);
            return false;
        });
    },
    tabCloseEven:function () {
        //刷新
        $('#tab-refresh').click(function(){
            var currTab = $('#tabs').tabs('getSelected');
            var url = $(currTab.panel('options').content).attr('src');
            $('#tabs').tabs('update',{
                tab:currTab,
                options:{
                    content: base.createFrame(url)
                }
            })
        })
        //关闭当前
        $('#tab-close').click(function(){
            var currtab_title = $('#tab-menu').data("currtab");
            $('#tabs').tabs('close',currtab_title);
        })
        //全部关闭
        $('#tab-close-all').click(function(){

            $('.tabs-inner span').each(function(i,n){
                var t = $(n).text();
                if(t != '欢迎使用'){
                    $('#tabs').tabs('close',t);
                }
            });
        });
        //关闭除当前之外的TAB
        $('#tab-close-other').click(function(){
            $('#tab-close-right').click();
            $('#tab-close-left').click();
        });
        //关闭当前右侧的TAB
        $('#tab-close-right').click(function(){
            var nextall = $('.tabs-selected').nextAll();
            if(nextall.length==0){
                msgShow('系统提示','后边没有啦~~','error');
                return false;
            }
            nextall.each(function(i,n){
                var t=$('a:eq(0) span',$(n)).text();
                if(t != '欢迎使用'){
                    $('#tabs').tabs('close',t);
                }
            });
            return false;
        });
        //关闭当前左侧的TAB
        $('#tab-close-left').click(function(){
            var prevall = $('.tabs-selected').prevAll();
            if(prevall.length==0){
                msgShow('系统提示','到头了，前边没有啦~~','error');
                return false;
            }
            prevall.each(function(i,n){
                var t=$('a:eq(0) span',$(n)).text();
                if(t != '欢迎使用'){
                    $('#tabs').tabs('close',t);
                }
            });
            return false;
        });

    }
}

// 创建基础数据缓存 全局变量
function initCommonDataCache() {
    // 字典数据缓存
    if((typeof store.get('sys-common-dict')) == 'undefined'){
        var param = {
            url: constant.route.dict.query
        }
        var request = http.get(param);
        request.done(function (data) {
            store.set('sys-common-dict', data.result);
        })
    }



    // 系统模块(子系统)
    if((typeof store.get('sys-common-module')) == 'undefined'){
        var paramModule = {
            url: constant.route.module
        }
        var request = http.get(paramModule);
        request.done(function (data) {
            store.set('sys-common-module', data.result.rows);
        })
    }


    // 角色信息
    if((typeof store.get('sys-common-role')) == 'undefined') {
        var param = {
            url: constant.route.role
        };
        var request = http.get(param);
        request.done(function (d) {
            store.set('sys-common-role', d.result);
        })
    }
}

// 退出
function exitSys() {
    setTimeout(function () {
        window.location.href = '/';
    }, 3000)
}


var log = {
    title:'api请求统计',
    toolbar:'#table-opt-btn',
    rownumbers: true,
    pagination: false,
    columns:[
        [
            {field:'classMethod',title:'函数', align:'left', width:300},
            {field:'method',title:'请求类型', align:'center',width:100},
            {field:'total',title:'请求次数', align:'center',width:100}
        ]
    ]
}

function getLog() {
    $('#log-view').css('height', kit.wh().height - 230);
    var day = $('#query-day').combobox("getValue");
    var param = {
        url: constant.route.log + '-api/' + day
    };
    var request = http.get(param);
    request.done(function (d) {
        log.data = d.result;
        component.datagrid.init('#table-list', log, false);
    })
}
function getCount() {

    var param = {
        url: constant.route.log + '-count'
    };
    var request = http.get(param);
    request.done(function (d) {
        var data = d.result;
        $('#count-total').html(data.total);
        $('#count-yesterday').html(data.yesterday);
        $('#count-today').html(data.today);
        $('#count-login').html(data.loginCount);
    })
}